module Ascii
  (
    getAsciiWeight,
    getHuffmanWeight,
    splitWithChar,
    getAsciiWeightTuple
  ) where

import Data.Char (ord, chr)
import Data.List (group, sort)

getCharCount :: Char -> [Char] -> Int
getCharCount c str = foldl (foo c) 0 str
  where foo = \c1 count c2 ->
                if c1 == c2
                then count+1
                else count

-- [Int] caintains weight for each character
getAsciiWeight :: [Char] -> [Int]
getAsciiWeight str = [length x| x<-group $ sort str]

getAsciiWeightTuple :: [Char] -> [(Int, Char)]
getAsciiWeightTuple str = [(length x, head x)| x<- group $ sort str]

-- change weight into huffman mode
showHuffPattern :: [(Int, Char)] -> [Char]
showHuffPattern weightPairs = foldl foo "" weightPairs
  where foo str pair = if fst pair /= 0
                       then str ++ show (fst pair) ++ [snd pair] ++ " "
                       else str

splitWithChar :: Char -> String -> [String]
splitWithChar c str = if str /= ""
                      then [splitedStr] ++ splitWithChar c (drop (length splitedStr + 1) str)
                      else []
  where splitedStr = takeWhile (/=c) str

-- "abcd" -> "1a 1b 1c 1d "
getHuffmanWeight :: [Char] -> [Char]
getHuffmanWeight = showHuffPattern . getAsciiWeightTuple
